package com.cheng.im.gateway.handler;

import com.cheng.im.common.bean.msg.ProtoMsg;
import com.cheng.im.common.bean.msg.ProtoMsgV1;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
@Component
@ChannelHandler.Sharable
public class SensitiveWordHandler  extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 判断消息实例
        if (null == msg || !(msg instanceof ProtoMsgV1.Message))
        {
            super.channelRead(ctx, msg);
            return;
        }

        // 判断消息类型
        ProtoMsgV1.Message pkg = (ProtoMsgV1.Message) msg;
        ProtoMsgV1.HeadType headType = ((ProtoMsgV1.Message) msg).getType();
        if (!headType.equals(ProtoMsgV1.HeadType.MESSAGE_REQUEST))
        {
            super.channelRead(ctx, msg);
            return;
        }

        // boolean contains = SensitiveWordHelper.contains(pkg.getMessageRequest().getContent());

        // todo: 需要重新构建或者修改原消息
        String replace = SensitiveWordHelper.replace(pkg.getMessageRequest().getContent());
        if (!StringUtils.isEmpty(replace)) {
//            ProtoMsg.Message.Builder builder = pkg.toBuilder();

            ProtoMsgV1.MessageRequest.Builder mb = pkg.getMessageRequest().toBuilder();
            mb.setContent(replace);
            ProtoMsgV1.Message build = pkg.toBuilder().setMessageRequest(mb).build();

            List<String> all = SensitiveWordHelper.findAll(pkg.getMessageRequest().getContent());
            log.info("敏感词：" + all.toString());

            super.channelRead(ctx, build);
            return;
        }

        super.channelRead(ctx, msg);
    }
}
